
/*
  Author Jinzhu.Zhang 2020.3
  使用
  Sing(qu,0)
*/

var audioCtx = new AudioContext();
var tone=[
 262.00, 294.00, 330.00, 349.00, 392.00, 440.00, 494.00,
 523.00, 587.00, 659.00, 698.00, 784.00, 880.00, 988.00,
1046.00,1175.00,1318.00,1397.00,1568.00,1760.00,1967.00
];
/*
曲谱编码：
（1）第一字符
abcdefg1234567ABCDEFG
              .......
123456712345671234567
.......
（2）第二字符
1      2   3   4 5 6 7 8  9
1/16,1/8,1/4,1/2,1,2,4,8,16
（3）双字符序列成谱

附：
乐谱：7*7=49个
a~z+A~Z=52个足够,X,Y,Z预留音

*/
var qu={
	name:'沧海一声笑',
	pu:'6553342416362313f3g5e5f3e5f315233252'
}
function Play(freq,beat) {
	var oscillator = audioCtx.createOscillator();
	var gainNode = audioCtx.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(audioCtx.destination);
    oscillator.type = 'sine';
    oscillator.frequency.value = freq;
    gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
    gainNode.gain.linearRampToValueAtTime(1, audioCtx.currentTime + 0.01);
    oscillator.start(audioCtx.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + beat);
    oscillator.stop(audioCtx.currentTime + beat);
}
var getBeat=function(c){
	switch(c){
		case '1':return 1/16;break
		case '2':return 1/ 8;break
		case '3':return 1/ 4;break
		case '4':return 1/ 2;break
		case '5':return    1;break
		case '6':return    2;break
		case '7':return    4;break
		case '8':return    8;break
		case '9':return   16;break
		default:break
	}
}
var getFreq=function(c){
	var d=c.charCodeAt()
	if(d>=65 && d<=71)return tone[d-65+14]
	if(d>=97 && d<=103)return tone[d-97]
	if(d>=49 && d<=55)return tone[d-49+7]
	return tone[0]
}
var sing=function(q,i){
	var freq=getFreq(q.pu[i])
	var beat=getBeat(q.pu[i+1])
	Play(freq, beat)
	setTimeout(function(oq,oi){
		if(oi<oq.pu.length-2)sing(oq,oi+2)
	},Math.floor(beat*1000),q,i)
}